from flask import current_app
from app.extensions import db, flask_redis
from app import create_app
from app.models.orders import Orders
from app.models.bills import Bills
import json
import pickle
import requests
from urllib import parse

app = create_app()

def response(flow):
    if 'wx.tenpay.com/userroll/userrolllist' in flow.request.url:

        print(flow.response.text)
        if not flask_redis.exists('user_1'):
            query = parse.parse_qs(flow.request.url.split('?')[1])
            print(query)
            csrf_token = query['csrf_token'][0]
            exportkey = query['exportkey'][0]
            flask_redis.hmset('user_1', {
                'cookies': pickle.dumps(flow.request.cookies.items(multi=True)),
                'csrf_token': csrf_token,
                'exportkey': exportkey
            })

        # res = requests.get(
        #     'https://wx.tenpay.com/userroll/userrolllist?classify_type=0&count=20&csrf_token=eh%2FPBcfqU7A%2BLA227R38mWSrXwCn2m5B&exportkey=AS0ZpJ7X5o2U%2Bvy7OLVoclQ%3D&sort_type=1',
        #     cookies=dict(pickle.loads(flask_redis.get('user_1')))
        #     )
        # print(res.text)
        
            

# def response(flow):
#     if 'wx.tenpay.com/userroll/userrolllist' in flow.request.url:
#         with app.app_context():
#             # 数据的解析
#             for item in json.loads(flow.response.text)['record']:
#                 bill = Bills()
#                 bill.title = item['title']
#                 bill.payer_wxid = item['payer_wxid']
#                 bill.out_trade_no = item['out_trade_no']
#                 bill.timestamp = item['timestamp']
#                 bill.fee = item['fee']
#                 bill.remark = item['remark']
#                 bill.payer_remark = item['payer_remark']
#                 db.session.add(bill)

#             try:
#                 db.session.commit()
#             except Exception as e:
#                 db.session.rollback()
#                 flash('未执行成功，请联系管理员', 'danger')
#                 raise e
            